import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

// 轮播图
import 'package:flutter_swiper/flutter_swiper.dart';

// flutter 屏幕适配方案，让你的UI在不同尺寸的屏幕上都能显示合理的布局!
import '../../services/ScreenAdapter.dart';

import '../../config/Config.dart';

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => HomePageState();
}

class HomePageState extends State with AutomaticKeepAliveClientMixin {
  List _focusList = [];
  List _hotProductList = [];
  List _bestProductList = [];

  //  缓存
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();

    //  获取轮播图图片数据
    _getFocusData();

    // 获取热门商品数据
    _getHotProductData();

    // 获取热门推荐商品数据
    _getBestProductData();

  }

  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init(context);

    return ListView(children: [
      // 轮播图
      Container(
        child: AspectRatio(
          aspectRatio: 2 / 1,
          child: _swiperWidget(),
        ),
      ),
      SizedBox(height: ScreenAdapter.height(20)),

      //  猜你喜欢
      _titleWidget('猜你喜欢'),
      SizedBox(height: ScreenAdapter.height(20)),

      // 猜你喜欢商品列表
      _hotProductListWidget(),
      SizedBox(height: ScreenAdapter.height(20)),

      //  热门推荐
      _titleWidget('热门推荐'),
      SizedBox(height: ScreenAdapter.height(20)),

      //  热门推荐商品列表
      Container(
        padding: EdgeInsets.all(10),
        child: Wrap(
          runSpacing: 10,
          spacing: 10,
          children: _bestProductList.map((value){
            return _recProductItemWidget(value);
          }).toList(),
        ),
      ),
    ]);
  }

  //  获取轮播图图片数据
  _getFocusData() async {
    var api = '${Config.domain}api/focus';
    var focusData = await Dio().get(api);
    var res = focusData.data["result"];
    this.setState(() {
      _focusList = res;
    });
  }

  // 获取猜你喜欢商品数据
  _getHotProductData() async {
    var api = '${Config.domain}api/plist?is_hot=1';
    var focusData = await Dio().get(api);
    var res = focusData.data["result"];
    this.setState(() {
      _hotProductList = res;
    });
  }

  //  获取热门推荐商品数据
  _getBestProductData() async {
    var api = '${Config.domain}api/plist?is_best=1';
    var focusData = await Dio().get(api);
    var res = focusData.data["result"];
    this.setState(() {
      _bestProductList = res;
    });
  }

  // 轮播图
  Widget _swiperWidget() {
    return Swiper(
      itemBuilder: (BuildContext context, int index) {
        String pic = _focusList[index]['pic'];
        return new Image.network(
          '${Config.domain + pic.replaceAll('\\', '/')}',
          fit: BoxFit.fill,
        );
      },
      itemCount: _focusList.length,
      pagination: SwiperPagination(),
      autoplay: true,
    );
  }

  //  左边红边的title
  Widget _titleWidget(title) {
    return Container(
      height: ScreenAdapter.height(42),
      margin: EdgeInsets.only(left: ScreenAdapter.width(20)),
      padding: EdgeInsets.only(left: ScreenAdapter.width(20)),
      decoration: BoxDecoration(
          border: Border(
              left: BorderSide(
        width: ScreenAdapter.width(10),
        color: Colors.red,
      ))),
      child: Text(title, style: TextStyle(color: Colors.black54, fontSize: 12)),
    );
  }

  // 猜你喜欢商品列表
  Widget _hotProductListWidget() {
    return Container(
      height: ScreenAdapter.height(200),
      padding: EdgeInsets.only(right: ScreenAdapter.width(20)),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemBuilder: (context, index) {
          String sPic = _hotProductList[index]['s_pic'];

          return Column(
            children: [
              Container(
                height: ScreenAdapter.height(160),
                width: ScreenAdapter.width(160),
                margin: EdgeInsets.only(left: ScreenAdapter.height(20)),
                child: Image.network(
                  '${Config.domain + sPic.replaceAll('\\', '/')}',
                  fit: BoxFit.cover,
                ),
              ),
              Text('￥ ${_hotProductList[index]['price']}',
                  style: TextStyle(fontSize: 12, color: Colors.black54))
            ],
          );
        },
        itemCount: _hotProductList.length,
      ),
    );
  }

  //  热门推荐商品列表
  Widget _recProductItemWidget(value) {
    var itemWidth = (ScreenAdapter.getScreenWidth() - 30) / 2;
    String sPic = value['s_pic'];

    return InkWell(
      child: Container(
        padding: EdgeInsets.all(5),
        width: itemWidth,
        decoration: BoxDecoration(
            border: Border.all(
              color: Colors.black12,
            )),
        child: Column(
          children: [
            Container(
              width: double.infinity,
              child: AspectRatio(
                aspectRatio: 1/1,
                child: Image.network(
                    '${Config.domain + sPic.replaceAll('\\', '/')}',
                    fit: BoxFit.cover),
              ),
            ),
            Container(
              alignment: Alignment.center,
              height: 70,
              child: Text('${value['title']}',
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(fontSize: 12, color: Colors.black54)),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('￥${value['price']}', style: TextStyle(color: Colors.red)),
                Text('￥${value['old_price']}',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.black54,
                      decoration: TextDecoration.lineThrough,
                    )),
              ],
            )
          ],
        ),
      ),
      onTap: (){
        Navigator.pushNamed(context,'/ProductContent',arguments:{
          "id": value['_id']
        });
      },
    );
  }
}
